<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, maximum-scale=1.0, initial-scale=1, user-scalable=0">
        <!-- 引入样式文件 -->
        <link rel="stylesheet" href="{{ asset('css/vant.index.css') }}"/>
        <script src="{{ asset('js/rem.js') }}"></script>
        <title>数治科技-聊天</title>
        <style>
            *{padding: 0;margin: 0;}
            button,a{outline: none;border: none;}
            button, input, textarea{font: small-caption !important}
            .wrap-view{width: 100%;height: calc(100vh);padding-bottom: 1.2rem;box-sizing: border-box;}
            .dialog-view{width: 100%;height:100%;background: #f5f5f5; padding: .24rem .32rem; box-sizing: border-box;overflow: auto;}
            .timeview{font-size: .22rem;color: #666;text-align: center;margin-bottom: .3rem;}
            .chatview{display: flex;flex-direction: row; }
            .chatview img{width: .8rem;height: .8rem; border-radius: 50%; background-size: contain; padding: 0 0.1rem;}
            .chat-content{font-size: .24em;padding: .2rem;margin-bottom: .3rem; background-color: #e6e6e6;color: #333;border-radius:0.2rem}
            .chatleft{align-items: flex-start; display: flex;}
            .chatright{margin-left: .1rem;}
            .chatright .name{font-size: .26rem; color: #555; margin-bottom: .2rem;}
            .chatview.rightview{justify-content: flex-end;}
            .chatview.rightview .chat-content{background-color: #5bc9a1;color: #ffffff;}
            .chatview.rightview .name{text-align: right;}
            .sendwrap{padding: .15rem .32rem;}
            .sendview{display: flex;flex-direction: row;align-items: center;}
            .sendview .input{width: 100%;height: .6rem;border:1px solid #e8e8e8; border-radius: .1rem; padding-left: 0.2rem;}
            .sendbtn{width: 1rem;height: .5rem;border-radius: .15rem;color: #ffffff;background-color: #5bc9a1; line-height: .5rem;
                text-align: center;flex-shrink: 0;margin-left: .2rem;}
        </style>
    </head>
    <body>
        <div class="wrap-view">
            <div class="dialog-view" id="dialog-view">
                <!-- <div class="timeview">2020-09-20 06:50</div> -->
                @if(!empty($chatRecords))
                    @foreach($chatRecords as $k => $record)
                        @if($userId != $record['userid'])
                            <div class="chatview leftview">
                                <div class="chatleft">
                                    <img src="{{$record['avatar']}}" alt="{{$record['username']}}">
                                </div>
                                <div class="chatright">
                                    <div class="name">{{$record['username']}}</div>
                                    <div class="chat-content">
                                        {{$record['content']}}
                                    </div>
                                </div>
                            </div>
                            @else
                            <div class="chatview rightview">
                                <div class="chatright">
                                    <div class="name">{{$record['username']}}</div>
                                    <div class="chat-content">
                                        {{$record['content']}}
                                    </div>
                                </div>
                                <div class="chatleft">
                                    <img src="{{$record['avatar']}}" alt="{{$record['username']}}">
                                </div>
                            </div>
                        @endif
                    @endforeach
                @endif
            </div>
            <div class="sendwrap">
                <div class="sendview">
                    <input type="text" id="chat-text" class="input">
                    <button id="sendMsg" class="sendbtn">发送</button>
                </div>
            </div>
        </div>
    </body>

    <!-- 引入 Vue 和 Vant 的 JS 文件 -->
    <script src="{{ asset('js/url.min.js') }}"></script>
    <script src="{{ asset('js/vue.min.js') }}"></script>
    <script src="{{ asset('js/vant.min.js') }}"></script>
    <script src="{{ asset('js/jquery.min.js') }}"></script>

    <script>
        var ws;
        var timeConnect = 0;
        var data = {
            roomId: url('?roomid'),
            client: url('?client'),
            userId: url('?userid'),
        }

        const toast = vant.Toast.loading({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });

        // 滚动到最后一条消息
        function toLastMessage() {
            var dialogView = document.getElementById('dialog-view');
            dialogView.scrollTop = dialogView.scrollHeight;
        }

        // 发送消息
        function sendMsg() {
            var content = $('#chat-text').val()
            var result = Object.assign(data, {type: 'say', content: content})
            ws.send(JSON.stringify( result ))
            $('#chat-text').val('')
        }

        // webSocket初始化
        function webSocketInit() {

            ws = new WebSocket("ws://qywechat.dtx-tech.com:5200");

            ws.onopen = function(evt) {
                var result = Object.assign(data, {type: 'login'})
                console.log("websocket握手成功，发送登录数据:"+data);
                ws.send(JSON.stringify( result ));
                toast.clear()
            };

            ws.onmessage = function(evt) {
                var msg = JSON.parse(evt.data);
                switch (msg.type) {
                    case 'error':
                        alert(msg.msg)
                        ws.close()
                        break;
                    case 'say':
                        if (data.roomId == msg.room_id) {
                            if (data.userId == msg.userid) {
                                view = '<div class="chatview rightview">' +
                                    '<div class="chatright">' +
                                        '<div class="name">'+ msg.username +'</div>' +
                                        '<div class="chat-content">'+ msg.content +'</div>' +
                                    '</div>' +
                                    '<div class="chatleft">' +
                                        '<img src="'+ msg.avatar +'" alt="'+ msg.username +'">' +
                                    '</div>' +
                                '</div>'
                            } else {
                                view = '<div class="chatview leftview">' +
                                    '<div class="chatleft">' +
                                        '<img src="'+ msg.avatar +'" alt="'+ msg.username +'">' +
                                    '</div>' +
                                    '<div class="chatright">' +
                                        '<div class="name">'+ msg.username +'</div>' +
                                        '<div class="chat-content">'+ msg.content +'</div>' +
                                    '</div>' +
                                '</div>'
                            }
                            $('.dialog-view').append(view)
                            toLastMessage()
                        }
                    break;
                }
            };

            ws.onclose = function(evt) {
                console.log("Connection closed.");
                reconnect();
            };
        }

        // 重连
        function reconnect() {
            // lockReconnect加锁，防止onclose、onerror两次重连
            timeConnect++;
            console.log("第" + timeConnect + "次重连");
            // 进行重连
            setTimeout(function () {
                webSocketInit();
            }, 1000);

        }

        $(function () {
            toLastMessage()
            webSocketInit()
            // input 监听回车事件
            $("#chat-text").keydown(function (e){
                // 当 keyCode 是13时,是回车操作
                if (e.keyCode == 13){
                    sendMsg()
                    // 取消之前的keydown事件
                    e.preventDefault();
                }
            })
            $('#sendMsg').click(function () {
                sendMsg()
            })
        })
    </script>
</html>
